import datetime
import os
import re
import asyncio
import pandas as pd
#import easyocr
import pytz
from PIL import Image, ImageEnhance
from aiogram import types
from aiogram.fsm.context import FSMContext
from aiogram.types import Message, InlineKeyboardButton, InlineKeyboardMarkup
from icecream import ic

import http_rest

authors = {}


async def cont_read(text: str):
    if len(text) == 4:
        matches = re.findall(r'^\d{4}$', text)
    else:
        matches = re.findall(r'^\d{5}$', text)
    return matches


async def cont_read10(text: str):
    matches = re.findall(r'^[a-zA-Z0-9]{4}\d{7}$', text)
    return matches


async def verify_tg_user(data: str):
    text_request = {
        "filter": "ИдентификаторТ eq `" + data + "` and Контрагент_Type eq `StandardODATA.Catalog_Сотрудники`"}
    request = await http_rest.send_odata_get("InformationRegister_ТелеграмПодписки", text_request)
    return request


async def image_enchance(images: Image):
    image= Image.open(images)
    enhancer = ImageEnhance.Contrast(image)
    image = enhancer.enhance(2.0)
    new_name = os.path.splitext(images)[0] + '-enhance' + os.path.splitext(images)[1]
    image.save(new_name)
    os.remove(images)
    return new_name


async def ocr(images):
    image = await image_enchance(images)
    reader = easyocr.Reader(['en'])
    result = reader.readtext(image, detail=0, paragraph=True)
    conteiner_number = re.sub(r'\W+', '', result[0])
    os.remove(image)
    return conteiner_number


async def inform_cont(dict_):
    str_info = '''
    ________________________________
    Номер контейнера: {number_cont}
    Температура: {temperature}
    Ошибки: {errors_ref}
    повреждения: {destroyed}
    '''
    return str_info.format(**dict_)


async def curent_date():
    timezone = pytz.timezone('Europe/Moscow')  # Замените 'Europe/Moscow' на вашу временную зону
    current_datetime = datetime.datetime.now(timezone)
    formatted_date = current_datetime.strftime("%H:%M %d.%m.%Y")  # Форматируем дату и время
    return formatted_date


async def a_send_data(callback_query: types.CallbackQuery, state: FSMContext, long_text: dict):
    chat_id = callback_query.message.chat.id
    await asyncio.sleep(1)
    update_req = await http_rest.send_odata_post('Document_РаботаСРефКонтейнерами', long_text)
    if update_req == 'Ошибка':
        bot_message = await callback_query.bot.send_message(chat_id, 'Произошла ошибка')
        await asyncio.sleep(5)
        await bot_message.delete()
    else:
        bot_message = await callback_query.bot.send_message(chat_id, 'Данные отправлены')
        await asyncio.sleep(5)
        await bot_message.delete()
